<script lang="ts" setup name="protable">
import { reactive } from "vue";
import { get, post } from "@/api/http";

export interface Column {
  label: string;
  prop: string;
  width?: number;
  align?: "center" | "left" | "right";
  format?: (T: string | number) => string | number;
}

export interface Props {
  columns: Column[];
  data: any[];
  operate?: any;
  scroll?: any;
  hieddenHeader?: boolean;
  extraBtns?: number;
}

export interface Modal {
  open: boolean;
  value: any;
}
const props = defineProps<Props>();
const emit = defineEmits(["update"]);

const updateTable = () => emit("update");

// const operateLabels = Object.keys(props.operate);

const modal = reactive<Modal>({
  open: false,
  value: {},
});

const delLoading: boolean = false;

const isFn = (val: unknown) => toString.call(val) === `[object Function]`;

const onDelete = (done: Function) => {
  const delFnOrPath = props.operate["删除"];
  if (isFn(delFnOrPath)) {
    done();
    delFnOrPath();
    return;
  }
  post(delFnOrPath, {}, "删除", delLoading)
    .then(() => {
      updateTable();
      modal.value = false;
    })
    .finally(() => done());
};

const formatColor = (text: string) => {
  if (["是", "正常", "开放中"].includes(text)) return "text-emerald";
  if (text === "否") return "text-red-5";
};
</script>

<template>
  <a-table
    stripe
    :show-header="props.hieddenHeader ? false : true"
    size="small"
    :pagination="false"
    :data="props.data"
    :scroll="props.scroll || {}"
  >
    <template #columns>
      <a-table-column
        v-for="(item, i) in props.columns"
        :key="item.prop + i"
        :title="item.label"
        :data-index="item.prop"
        :align="item.align || 'center'"
        :width="item.width"
        ellipsis
        tooltip
      >
        <template #cell="{ record }">
          <!-- 格式化内容 -->
          <template v-if="item.prop == 'sex'">
            <span>{{ record["sex"] ? "男" : "女" }}</span>
          </template>
          <template v-else>
            <span
              v-if="item.format"
              :class="formatColor(item.format(record[item.prop]))"
              >{{ item.format(record[item.prop]) }}</span
            >
            <span :class="formatColor(record[item.prop])" v-else>{{
              record[item.prop]
            }}</span>
          </template>
        </template>
      </a-table-column>
    </template>
  </a-table>

  <!-- 确认框 -->
  <a-modal
    v-model:visible="modal.open"
    title="提示"
    @cancel="modal.open = false"
    @before-ok="onDelete"
  >
    <div class="text-center">
      <span class="tracking-1px">确认删除{{ modal.value.name }}吗？</span>
    </div>
  </a-modal>
</template>

<style lang="less" scoped></style>
